package controllers;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import com.ebay.sdk.ApiCall;
import com.ebay.sdk.ApiContext;
import com.ebay.sdk.ApiCredential;
import com.ebay.sdk.ApiException;
import com.ebay.sdk.SdkException;
import com.ebay.sdk.call.AddFixedPriceItemCall;
import com.ebay.sdk.call.AddItemCall;
import com.ebay.sdk.call.EndItemCall;
import com.ebay.sdk.call.GetItemCall;
import com.ebay.sdk.call.GetProductSearchResultsCall;
import com.ebay.sdk.call.GetProductsCall;
import com.ebay.sdk.call.GetSellerListCall;
import com.ebay.sdk.call.GeteBayOfficialTimeCall;
import com.ebay.sdk.util.eBayUtil;
import com.ebay.sdk.TimeFilter;
import com.ebay.services.client.ClientConfig;
import com.ebay.services.client.FindingServiceClientFactory;
import com.ebay.services.finding.FindItemsByKeywordsRequest;
import com.ebay.services.finding.FindItemsByKeywordsResponse;
import com.ebay.services.finding.FindingServicePortType;
import com.ebay.services.finding.ItemFilter;
import com.ebay.services.finding.ItemFilterType;
import com.ebay.services.finding.OutputSelectorType;
import com.ebay.services.finding.ProductId;
import com.ebay.services.finding.SearchItem;
import com.ebay.soap.eBLBaseComponents.AbstractRequestType;
import com.ebay.soap.eBLBaseComponents.AbstractResponseType;
import com.ebay.soap.eBLBaseComponents.AmountType;
import com.ebay.soap.eBLBaseComponents.BuyerPaymentMethodCodeType;
import com.ebay.soap.eBLBaseComponents.CatalogProductType;
import com.ebay.soap.eBLBaseComponents.CategoryType;
import com.ebay.soap.eBLBaseComponents.CharacteristicsSetProductHistogramType;
import com.ebay.soap.eBLBaseComponents.CountryCodeType;
import com.ebay.soap.eBLBaseComponents.CurrencyCodeType;
import com.ebay.soap.eBLBaseComponents.DataElementSetType;
import com.ebay.soap.eBLBaseComponents.DetailLevelCodeType;
import com.ebay.soap.eBLBaseComponents.EndReasonCodeType;
import com.ebay.soap.eBLBaseComponents.ExternalProductCodeType;
import com.ebay.soap.eBLBaseComponents.ExternalProductIDType;
import com.ebay.soap.eBLBaseComponents.FeesType;
import com.ebay.soap.eBLBaseComponents.GetProductsRequestType;
import com.ebay.soap.eBLBaseComponents.GranularityLevelCodeType;
import com.ebay.soap.eBLBaseComponents.HistogramEntryType;
import com.ebay.soap.eBLBaseComponents.ItemArrayType;
import com.ebay.soap.eBLBaseComponents.ItemType;
import com.ebay.soap.eBLBaseComponents.ListingDurationCodeType;
import com.ebay.soap.eBLBaseComponents.ListingTypeCodeType;
import com.ebay.soap.eBLBaseComponents.ProductListingDetailsType;
import com.ebay.soap.eBLBaseComponents.ProductSearchResultType;
import com.ebay.soap.eBLBaseComponents.ProductSearchType;
import com.ebay.soap.eBLBaseComponents.ProductSortCodeType;
import com.ebay.soap.eBLBaseComponents.ReturnPolicyType;
import com.ebay.soap.eBLBaseComponents.ShippingDetailsType;
import com.ebay.soap.eBLBaseComponents.ShippingServiceCodeType;
import com.ebay.soap.eBLBaseComponents.ShippingServiceOptionsType;
import com.ebay.soap.eBLBaseComponents.ShippingTypeCodeType;
import java.util.Locale;
import java.net.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.text.DecimalFormat;

public class Api {

    static final String TOKEN = "AgAAAA**AQAAAA**aAAAAA**2NrfTg**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6wFk4GhCJKEow6dj6x9nY+seQ**+YIBAA**AAMAAA**ezWKC5RiXjG5Xsn89bmfgha5/MX4ZujSmZqSEnVrh/4qchAL5NYCMpAGocaCbclIVnynrU1TdVv/MoUP/R6oq7UMduHSBYjx/7JE7FKAMc24CfgFQd8kzW/MrzX7IFwwpsk6q10nnEl+2h31GvQolVfBB00lHwRAWXNosNacCWn3MGtL+M4wHQUMrFFxtYdeIrOosZki5nPBY4iRk2smhLNsz3DNd2QiAxD7EW/nrlD879UXMmwqbighbBJ03pDo1nAWWQYN5KmaBv0ufUu3SMgUgC9hdAARBK1qSBx+T1E+fJwQUl5HBT/CSY4DLa0y2XjU2PqOA7GZ5eigEj0PpeWxzGyi/PEnIykJvzgm30TSFxIHOlQW6VM3zSKfVy7wtIWgoQ82zFb62oL6BrNJTIzoYdP4Mjy/IgKarpJyAVgoe4/p51fQ/tqFQ/qSchb9IbbUIDECjJHuJGIDHasOrnrvOjN5EpB5ELQ8qbJOfau0cfxtjtusfhJclDzq3LCSPk0lcz05uYtGYft3vQ1wgbFssAGHE7R3md3JGgYJbIIkbhGio/d7t9ql3oJscBnugD5I2nN74QzMmvCmqZzFFWeqHiabaR/A2z056cqQViv/OHhfIuwFteZulY/9qzXV6p3U/9jSlSr/32oZim5vvpCXbJkx4IYUg+dVre2aRaKMuEIooatrzPsEdhyUWz6jRF3w7Cht6yZF4yF9aQZ+AXzgAsNJbRPrBZFmCVqGoFUW5dxGdGTcYah1i5qY2+Tp";
    static final String SOAPURL = "https://api.sandbox.ebay.com/wsapi";
    static final String appID = "EricGust-68a6-4d27-9a6f-df11c1d1da25";
	static final String endPointAddress = "http://svcs.sandbox.ebay.com/services/search/FindingService/v1";
    ApiContext apiContext;
    ApiCredential apiCredential;

    public Api() {
        this.apiContext = new ApiContext();
        this.apiCredential = apiContext.getApiCredential();
        this.apiCredential.seteBayToken(TOKEN);
        this.apiContext.setApiServerUrl(SOAPURL);
    }

    /**
     * Get the official ebay time in String format
     *
     * @return String time
     * mainly for testing purposes.
     */
    public String getTimeString() {
        GeteBayOfficialTimeCall apiCall = new GeteBayOfficialTimeCall(this.apiContext);
        try {
            Calendar cal = apiCall.geteBayOfficialTime();
            return cal.getTime().toString();
        } catch (Exception e) {
            return "Unable to get time";
        }
    }

    public Calendar getTime() throws ApiException, SdkException, Exception {
        GeteBayOfficialTimeCall apiCall = new GeteBayOfficialTimeCall(this.apiContext);
        return apiCall.geteBayOfficialTime();
    }

    /**
     * List an item on ebay
     *
     * @return String itemID
     * returns the eBay-assigned itemID for that item.
     */
    public String addItem(String title, String isbn, String description, double itemPrice, double shippingPrice, ListingDurationCodeType duration) throws ApiException, SdkException, Exception {
        ItemType item = new ItemType();
        
        //Xiaoming modified
        ExternalProductIDType type = new ExternalProductIDType();
        type.setType(ExternalProductCodeType.ISBN);
        type.setValue(isbn);
        
        
        item.setTitle(title);
        item.setDescription(description);
        item.setListingType(ListingTypeCodeType.FIXED_PRICE_ITEM);
        item.setCurrency(CurrencyCodeType.USD);
        item.setLocation("Pittsburgh, PA");
        item.setCountry(CountryCodeType.US);
        item.setListingDuration(duration.value());
        item.setExternalProductID(type); //Xiaoming modified
        
        //set price
        AmountType amount = new AmountType();
        amount.setValue(itemPrice);
        item.setStartPrice(amount);
        item.setBuyItNowPrice(amount);

        //set the return policy
        ReturnPolicyType returnPolicy = new ReturnPolicyType();
        returnPolicy.setReturnsAcceptedOption("ReturnsAccepted");
        item.setReturnPolicy(returnPolicy);

        item.setConditionID(1000); // item condition, New

        // payment methods
        item.setPaymentMethods(new BuyerPaymentMethodCodeType[]{BuyerPaymentMethodCodeType.PAY_PAL});
        item.setPayPalEmailAddress("me@ebay.com");

        // handling time is required
        item.setDispatchTimeMax(Integer.valueOf(1));

        // shipping details
        item.setShippingDetails(buildShippingDetails(shippingPrice));

        // listing category
        CategoryType cat = new CategoryType();
        cat.setCategoryID("377"); //267 = books, 377 = fiction
        item.setPrimaryCategory(cat);

        // product listing details: isbn
        
        ProductListingDetailsType productListingDetails = new ProductListingDetailsType();
        productListingDetails.setISBN(isbn);
        productListingDetails.setStockPhotoURL("http://covers.openlibrary.org/b/isbn/"+ isbn +".jpg");
        productListingDetails.setIncludeStockPhotoURL(Boolean.TRUE);
        item.setProductListingDetails(productListingDetails);

        ExternalProductIDType externalProductID = new ExternalProductIDType();

        externalProductID.setType(ExternalProductCodeType.ISBN);
        externalProductID.setValue(isbn);
        item.setExternalProductID(externalProductID);

        AddFixedPriceItemCall addFixedPriceItemCall = new AddFixedPriceItemCall(apiContext);
        addFixedPriceItemCall.setItem(item);

        //TODO: add in the ability to add a picture
        
        addFixedPriceItemCall.addFixedPriceItem();
        
        
        return addFixedPriceItemCall.getReturnedItemID();

        /*
        FeesType fees = addFixedPriceItemCall.addFixedPriceItem();
        double listingFee = eBayUtil.findFeeByName(fees.getFee(),
                "ListingFee").getFee().getValue();

        //return the listing fee
        return new Double(listingFee).toString();
        */
    }

    /**
     * Gets the information for an item as if you were viewing it on eBay
     *
     * @param itemIDStr
     * @return ItemType object
     * @throws ApiException
     * @throws SdkException
     * @throws Exception
     */
    public ItemType viewItem(String itemIDStr) throws ApiException, SdkException, Exception {
        GetItemCall getItemCall = new GetItemCall(apiContext);
        DetailLevelCodeType[] detailLevels = new DetailLevelCodeType[]{
            DetailLevelCodeType.RETURN_ALL,
            DetailLevelCodeType.ITEM_RETURN_ATTRIBUTES,
            DetailLevelCodeType.ITEM_RETURN_DESCRIPTION
        };
        getItemCall.setDetailLevel(detailLevels);
        return getItemCall.getItem(itemIDStr);
    }

    /**
     * Gets all the items that are currently on auction.
     *
     * @return ItemType[]
     * @throws ApiException
     * @throws SdkException
     * @throws Exception
     */
    public ItemType[] getAllCurrentItems() throws ApiException, SdkException, Exception {
        GetSellerListCall getSellerListCall = new GetSellerListCall(apiContext);

        Calendar now = getTime();

        Calendar twoMonthsPast = Calendar.getInstance();
        twoMonthsPast.setTime(now.getTime());
        twoMonthsPast.add(Calendar.DATE, -60);

        Calendar twoMonthsFuture = Calendar.getInstance();
        twoMonthsFuture.setTime(now.getTime());
        twoMonthsFuture.add(Calendar.DATE, 60);

        TimeFilter endTimeFilter = new TimeFilter(now, twoMonthsFuture);
        getSellerListCall.setEndTimeFilter(endTimeFilter);

        TimeFilter startTimeFilter = new TimeFilter(twoMonthsPast, now);
        getSellerListCall.setStartTimeFilter(startTimeFilter);
        
        getSellerListCall.addDetailLevel(DetailLevelCodeType.RETURN_ALL);
        //getSellerListCall.setGranularityLevel(GranularityLevelCodeType.FINE);
        return getSellerListCall.getEntireSellerList();
    }

    /**
     * End a sale listing now. Deletes the listing from eBay.
     *
     * @param itemIDStr
     * @param endingReason
     * @throws ApiException
     * @throws SdkException
     * @throws Exception
     */
    public void removeItem(String itemIDStr, EndReasonCodeType endReasonCodeType) throws ApiException, SdkException, Exception {
        EndItemCall endItemCall = new EndItemCall(apiContext);
        endItemCall.setItemID(itemIDStr);
        endItemCall.setEndingReason(endReasonCodeType);
        endItemCall.endItem();
    }

    /**
     * Build shipping details (helper function)
     *
     * @return ShippingDetailsType object
     */
    private static ShippingDetailsType buildShippingDetails(double shippingPrice) {
        // Shipping details.
        ShippingDetailsType sd = new ShippingDetailsType();

        sd.setPaymentInstructions("eBay Java SDK test instruction.");

        // Shipping type and shipping service options
        sd.setShippingType(ShippingTypeCodeType.FLAT);
        ShippingServiceOptionsType shippingOptions = new ShippingServiceOptionsType();
        shippingOptions.setShippingService(ShippingServiceCodeType.SHIPPING_METHOD_STANDARD.value());

        AmountType amount = new AmountType();
        amount.setValue(shippingPrice);
        shippingOptions.setShippingServiceCost(amount);
        shippingOptions.setShippingServicePriority(new Integer(1));

        sd.setShippingServiceOptions(new ShippingServiceOptionsType[]{shippingOptions});

        return sd;
    }
   
    
   /**
    * 
    * @param keywords
    * @return
    * @throws ApiException
    * @throws SdkException
    * @throws Exception
    */
    public CatalogProductType[] searchProductsByKeywords(String keywords) throws ApiException, SdkException, Exception{
    	ProductSearchType productSearchType = new ProductSearchType();
        GetProductsCall getProductsCall = new GetProductsCall(apiContext);
        //set keywords
    	productSearchType.setQueryKeywords(keywords);
    	DetailLevelCodeType[] detailLevels = new DetailLevelCodeType[]{
                DetailLevelCodeType.RETURN_ALL,
                DetailLevelCodeType.ITEM_RETURN_ATTRIBUTES,
                DetailLevelCodeType.ITEM_RETURN_DESCRIPTION,
            };
        getProductsCall.setDetailLevel(detailLevels);
        getProductsCall.setProductSearch(productSearchType);
        getProductsCall.setProductSort(ProductSortCodeType.TITLE_ASC);
        getProductsCall.setIncludeItemArray(Boolean.TRUE);
     
        CharacteristicsSetProductHistogramType products = getProductsCall.getProducts();  
        return getProductsCall.getReturnedProduct();
    
    }
    
    /**
     * 
     * @param referenceID
     * @return
     * @throws ApiException
     * @throws SdkException
     * @throws Exception
     */
    public CatalogProductType[] searchProductsByReferenceID(String referenceID) throws ApiException, SdkException, Exception{
    	ProductSearchType productSearchType = new ProductSearchType();
        GetProductsCall getProductsCall = new GetProductsCall(apiContext);
        //set keywords
   // 	productSearchType.setProductReferenceID(referenceID);
    	productSearchType.setProductID(referenceID);
    	DetailLevelCodeType[] detailLevels = new DetailLevelCodeType[]{
                DetailLevelCodeType.RETURN_ALL,
                DetailLevelCodeType.ITEM_RETURN_ATTRIBUTES,
                DetailLevelCodeType.ITEM_RETURN_DESCRIPTION,
            };
        getProductsCall.setDetailLevel(detailLevels);
        getProductsCall.setProductSearch(productSearchType);
        getProductsCall.setProductSort(ProductSortCodeType.TITLE_ASC);
        getProductsCall.setIncludeItemArray(Boolean.TRUE);
     
        CharacteristicsSetProductHistogramType products = getProductsCall.getProducts();  
        return getProductsCall.getReturnedProduct();
    
    }
    
   /**
    * 
    * @param isbn
    * @return
    * @throws ApiException
    * @throws SdkException
    * @throws Exception
    */
    public  ItemArrayType searchProductsByISBN(String isbn)throws ApiException, SdkException, Exception{
    	ProductSearchType productSearchType = new ProductSearchType();
        GetProductsCall getProductsCall = new GetProductsCall(apiContext);
        ExternalProductIDType externalProductIDType = new ExternalProductIDType();
        externalProductIDType.setType(ExternalProductCodeType.ISBN);
        externalProductIDType.setValue(isbn);
        
        //set isbn
    	productSearchType.setExternalProductID(externalProductIDType);
    	DetailLevelCodeType[] detailLevels = new DetailLevelCodeType[]{
                DetailLevelCodeType.RETURN_ALL,
                DetailLevelCodeType.ITEM_RETURN_ATTRIBUTES,
                DetailLevelCodeType.ITEM_RETURN_DESCRIPTION,
            };
        getProductsCall.setDetailLevel(detailLevels);
        getProductsCall.setProductSearch(productSearchType);
        getProductsCall.setProductSort(ProductSortCodeType.TITLE_ASC);
        getProductsCall.setIncludeItemArray(Boolean.TRUE);
        getProductsCall.setIncludeHistogram(Boolean.TRUE);
        
        CharacteristicsSetProductHistogramType products = getProductsCall.getProducts(); 
        return getProductsCall.getReturnedItemArray();
      
    }
    
    
    /**
     * Get item by item ID
     * @return 
     * @throws Exception 
     * @throws SdkException 
     * @throws ApiException 
     * 
     */
    public ItemType getItemsByItemID(String itemID) throws ApiException, SdkException, Exception{
    	GetItemCall getItemCall = new GetItemCall(apiContext);
    	DetailLevelCodeType[] detailLevels = new DetailLevelCodeType[]{
                DetailLevelCodeType.RETURN_ALL,
                DetailLevelCodeType.ITEM_RETURN_ATTRIBUTES,
                DetailLevelCodeType.ITEM_RETURN_DESCRIPTION,
            };
    	getItemCall.setDetailLevel(detailLevels);
    	getItemCall.setItemID(itemID);
    	ItemType item = getItemCall.getItem();
    	return getItemCall.getReturnedItem();
    }
    
  
    /**
     * 
     * @param userID
     * @return
     * @throws ApiException
     * @throws SdkException
     * @throws Exception
     */
    
    public  ItemType[] searchProductsBySellerID(String userID) throws ApiException, SdkException, Exception{
    	GetSellerListCall getSellerListCall = new GetSellerListCall(apiContext);

        Calendar now = getTime();

        Calendar twoMonthsPast = Calendar.getInstance();
        twoMonthsPast.setTime(now.getTime());
        twoMonthsPast.add(Calendar.DATE, -60);

        Calendar twoMonthsFuture = Calendar.getInstance();
        twoMonthsFuture.setTime(now.getTime());
        twoMonthsFuture.add(Calendar.DATE, 60);

        TimeFilter endTimeFilter = new TimeFilter(now, twoMonthsFuture);
        getSellerListCall.setEndTimeFilter(endTimeFilter);

        TimeFilter startTimeFilter = new TimeFilter(twoMonthsPast, now);
        getSellerListCall.setStartTimeFilter(startTimeFilter);
        
        getSellerListCall.setUserID(userID);
       
        ItemType[] items = getSellerListCall.getEntireSellerList();
        
        return getSellerListCall.getReturnedItems();
    }

 
   /**
    *  
    * @param keywords
    * @return
    */
    public List<SearchItem> buyerSearchByKeywordFindingApi(String keywords){
    	// initialize service end-point configuration
    	ClientConfig config = new ClientConfig();
    	config.setApplicationId(appID);
    	config.setEndPointAddress(endPointAddress);
    	
    	//create a service client
        FindingServicePortType serviceClient = FindingServiceClientFactory.getServiceClient(config);
      
        FindItemsByKeywordsRequest request = new FindItemsByKeywordsRequest();
        request.setKeywords(keywords);
        request.getOutputSelector().add(OutputSelectorType.SELLER_INFO);
        request.getOutputSelector().add(OutputSelectorType.ASPECT_HISTOGRAM);
        request.getOutputSelector().add(OutputSelectorType.CATEGORY_HISTOGRAM);
        request.getOutputSelector().add(OutputSelectorType.CONDITION_HISTOGRAM);
        request.getOutputSelector().add(OutputSelectorType.STORE_INFO);
     
       
        
        ItemFilter itemFilter = new ItemFilter();   
        itemFilter.setName(ItemFilterType.SELLER);
        itemFilter.getValue().add(0, "testuser_monkey44");
        request.getItemFilter().add(itemFilter);
      
        FindItemsByKeywordsResponse result = serviceClient.findItemsByKeywords(request);
        
        List<SearchItem> items = result.getSearchResult().getItem();
    
        return items;
    }
    
    /*   
	public DataElementSetType[] getProductSearchResults(String keywords) throws ApiException, SdkException, Exception{
    	ProductSearchType[] productSearchType = new ProductSearchType[1];
   // 	productSearchType[1] = new ProductSearchType();
    	// set productSearchType = keywords
    	// here we can search for multiple different products at the same time
    	productSearchType[0].setQueryKeywords(keywords); 
    	GetProductSearchResultsCall getProductsSearchResultsCall = new GetProductSearchResultsCall(apiContext);
    	
    	DetailLevelCodeType[] detailLevels = new DetailLevelCodeType[]{
                DetailLevelCodeType.RETURN_ALL,
                DetailLevelCodeType.ITEM_RETURN_ATTRIBUTES,
                DetailLevelCodeType.ITEM_RETURN_DESCRIPTION,
            };
    	
    	getProductsSearchResultsCall.setDetailLevel(detailLevels);   
    	getProductsSearchResultsCall.setProductSearch(productSearchType);
    	ProductSearchResultType[] productSearchResultType = getProductsSearchResultsCall.getProductSearchResults();
    	 return getProductsSearchResultsCall.getReturnedDataElementSets();
    	
    }
  */  
    
    public int ericSearchProductsByKeywords(String keywords) throws ApiException, SdkException, Exception{
    	ProductSearchType productSearchType = new ProductSearchType();

        GetProductsCall getProductsCall = new GetProductsCall(apiContext);

    	//set keywords
    	productSearchType.setQueryKeywords(keywords);
    	DetailLevelCodeType[] detailLevels = new DetailLevelCodeType[]{
                DetailLevelCodeType.RETURN_ALL,
                DetailLevelCodeType.ITEM_RETURN_ATTRIBUTES,
                DetailLevelCodeType.ITEM_RETURN_DESCRIPTION,
            };
    	getProductsCall.setDetailLevel(detailLevels);
        getProductsCall.setProductSearch(productSearchType);
        getProductsCall.setProductSort(ProductSortCodeType.TITLE_ASC);
        getProductsCall.setIncludeItemArray(Boolean.TRUE);

        CharacteristicsSetProductHistogramType products = getProductsCall.getProducts();

        //ItemArrayType itemArrayType = getProductsCall.getReturnedItemArray();
        return getProductsCall.getReturnedTotalProducts();
    	//getProductsCall.getReturnedProduct();
    }
	
	
    /**
     * Obtain pricing research information using Research API
     *
     * @return output String containing array of data
     */
	public String priceResearch(String option, String keywords){
		String address = "http://api.dataunison.com/rest/?call_name=GetPriceResearch&AppID=DeniseTe-50aa-4d04-b13b-861de01a024c&Version=2&ResearchPeriod=30&QueryKeywords=" + keywords + "&IncludeDailyStatistics=true";
		
		//Output daily statistics for view
		String output = "";
		
		try{
			URL url = new URL(address);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			conn.setAllowUserInteraction(false);
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			Document xml = docBuilder.parse(conn.getInputStream());				

			
			//Read XML output
			if(xml != null){
				
				//Daily statistics data for this product
				NodeList dailyStatsList = xml.getElementsByTagName("DailyStatistics");
				if(dailyStatsList != null){
					for(int i=0; i<dailyStatsList.getLength(); i++){
						Element element = (Element)dailyStatsList.item(i);
						String date = element.getElementsByTagName("Date").item(0).getChildNodes().item(0).getNodeValue();
						date = date.substring(5,7) + "/" + date.substring(8);
						DecimalFormat df = new DecimalFormat("#");
						String totalSales = element.getElementsByTagName("TotalSales").item(0).getChildNodes().item(0).getNodeValue();
						double totalSalesTruncated = Double.valueOf(df.format(Double.parseDouble(totalSales)));
						totalSales = totalSalesTruncated + "";
						String totalSoldItems = element.getElementsByTagName("TotalSoldItems").item(0).getChildNodes().item(0).getNodeValue();
						String averageSoldPrice = element.getElementsByTagName("AverageSoldPrice").item(0).getChildNodes().item(0).getNodeValue();
						String maxSoldPrice = element.getElementsByTagName("MaxSoldPrice").item(0).getChildNodes().item(0).getNodeValue();
						String minSoldPrice = element.getElementsByTagName("MinSoldPrice").item(0).getChildNodes().item(0).getNodeValue();

						if(option.equals("total_sales")){
							output += "[" + totalSales + ",'" + date + "','#f3f3f3']";
						}else if(option.equals("total_sold_items")){
							output += "[" + totalSoldItems + ",'" + date + "','#f3f3f3']";
						}else if(option.equals("average_sold_price")){
							output += "[" + averageSoldPrice + ",'" + date + "','#f3f3f3']";
						}
						if(i != dailyStatsList.getLength()-1){
							output += ",";
						}
					}
				}
			}
		} catch (Exception e){
			e.printStackTrace();
		}
		
		return output;
	}
}